package com.focusai.efairy.ui.activity.project;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.focusai.efairy.R;
import com.focusai.efairy.model.request.AddDevToUserRequest;
import com.focusai.efairy.model.request.GetManageUserDevListRequest;
import com.focusai.efairy.model.response.ProjectManageResponse;
import com.focusai.efairy.network.HttpManager;
import com.focusai.efairy.network.Response;
import com.focusai.efairy.network.exception.NetworkException;
import com.focusai.efairy.ui.adapter.project.ProjectUserDevAdapter;
import com.focusai.efairy.ui.base.SwipeBackBaseActivity;
import com.focusai.efairy.utils.Constants;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by luo_guangwen on 2017/9/12.
 */

public class ProjectEditUserActivity extends SwipeBackBaseActivity implements View.OnClickListener {
    public static final String KEY_PROJECT_ID = "key_project_id";
    public static final String KEY_ITEM_USER = "key_item_user";
    private static final int REQUEST_CODE_DEV = 0X15;
    private RecyclerView mRecyclerView;
    private EditText text_user_name;
    private EditText text_user_phone;
    private TextView text_dev_num;
    private TextView text_add;
    private ProjectUserDevAdapter mAdapter;
    private ArrayList<ProjectManageResponse.DevItem> mList;
    private String projectId;
    private ProjectManageResponse.UserItem userItem;
    private boolean isShowDetail = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_project_edit_user);
        initView();
        setDefaultValues();
        loadData();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!isShowDetail){
            MenuItem menuItem1 = menu.add(MENU_GROUP_ID, MENU_ITEM_ADD, 0, R.string.save).setTitle(R.string.save);
            MenuItemCompat.setShowAsAction(menuItem1, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == MENU_ITEM_ADD) {
            addDevToUser();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void initView() {
        mRecyclerView = findView(R.id.rcyc_view);
        text_user_name = findView(R.id.text_user_name);
        text_user_phone = findView(R.id.text_user_phone);
        text_dev_num = findView(R.id.text_dev_num);
        text_add = findView(R.id.text_add);
        text_add.setText(getResources().getString(R.string.distribution_dev));
        findView(R.id.llayout_dev_manage).setOnClickListener(this);
    }

    @Override
    protected void setDefaultValues() {
        if (getIntent() != null && getIntent().getExtras() != null) {
            projectId = getIntent().getExtras().getString(KEY_PROJECT_ID);
            isShowDetail = getIntent().getExtras().getBoolean(Constants.KEY_DETAIL,false);
            userItem = (ProjectManageResponse.UserItem) getIntent().getExtras().getSerializable(KEY_ITEM_USER);
        }
        if (userItem == null) {
            showToast("传入的用户信息有误");
            finish();
            return;
        }
        setCenterTitleName("给用户分配设备");
        text_user_name.setText(userItem.efairyuser_nickname);
        text_user_phone.setText(userItem.efairyuser_phonenumber);
        text_user_phone.setEnabled(false);
        text_user_name.setEnabled(false);
        mList = new ArrayList<>();
        mAdapter = new ProjectUserDevAdapter();
        mAdapter.refreshData(mList);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(mAdapter);

    }

    @Override
    protected void loadData() {
        showSingleDialog("正在加载数据..");
        HttpManager.getInstance().sendRequest(new GetManageUserDevListRequest(projectId, userItem.efairyuser_id + "", new Response.Listener<ProjectManageResponse.UserDevItems>() {
            @Override
            protected void onSuccess(ProjectManageResponse.UserDevItems response) {
                closeSingleDialog();
                if (response != null && response.device_list != null) {
                    mList.clear();
                    mList.addAll(response.device_list);
                    mAdapter.notifyDataSetChanged();
                    text_dev_num.setText(getResources().getString(R.string.my_manager_device, mList.size()));
                }
            }

            @Override
            protected void onFail(NetworkException exception) {
                closeSingleDialog();
                doException(exception);
            }
        }));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llayout_dev_manage:
                Intent intent = new Intent(getContext(), ProjectSelectDevListActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable(ProjectSelectDevListActivity.KEY_SELETED_ITEMS, mList);
                bundle.putString(ProjectSelectDevListActivity.KEY_PROJECT_ID, projectId);
                intent.putExtras(bundle);
                startActivityForResult(intent, REQUEST_CODE_DEV);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_DEV) {
                if (data != null && data.getExtras() != null) {
                    ArrayList<ProjectManageResponse.DevItem> list = (ArrayList<ProjectManageResponse.DevItem>) data.getExtras()
                            .getSerializable(ProjectSelectDevListActivity.KEY_SELETED_ITEMS);
                    mList.clear();
                    mList.addAll(list);
                    mAdapter.notifyDataSetChanged();
                    text_dev_num.setText(getResources().getString(R.string.my_manager_device, mList.size()));
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void addDevToUser() {
        if (mList.size() == 0) {
            showToast("请选择设备");
            return;
        }
        List<Long> ids = new ArrayList<>();
        for (ProjectManageResponse.DevItem devItem : mList) {
            ids.add(devItem.efairydevice_id);
        }
        showSingleDialog("正在提交数据..");
        HttpManager.getInstance().sendRequest(new AddDevToUserRequest(projectId, "" + userItem.efairyuser_id, ids, new Response.Listener<String>() {
            @Override
            protected void onSuccess(String response) {
                closeSingleDialog();
                showToast("保存数据成功");
                setResult(RESULT_OK);
                finish();
            }

            @Override
            protected void onFail(NetworkException exception) {
                closeSingleDialog();
                doException(exception);
            }
        }));
    }
}
